package com.gosling.cloudspace.tools;

import org.apache.commons.lang3.StringUtils;

/**
 * 根据业务需要新增的综合工具类方法
 *
 * @author yanghongquan
 * @email 842592135@qq.com
 * @date 2019/7/4 9:22
 */
public class BankCardTool {

    /**
     * 校验银行卡卡号.
     */
    public static boolean checkBankCard(String cardId) {
        if (StringUtils.isBlank(cardId) || !cardId.matches("\\d+")) {
            throw new IllegalArgumentException("请输入有效的银行卡号!");
        }
        char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
        return cardId.charAt(cardId.length() - 1) == bit;
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
     */
    public static char getBankCardCheckCode(String nonCheckCodeCardId) {

        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

}
